package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"os/exec"
	"runtime"
	"strings"
	"sync"
)

var ipSucess []string
var ipFail []string

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	var wg sync.WaitGroup

	a := make(chan string)
	go operText("ip.txt", a)
	for v := range a {
		go func(v string) {
			wg.Add(1)
			pingCmd(v)

			wg.Done()
		}(v)

	}

	wg.Wait()
	fmt.Printf("\nTotle:%v  UP:%v  Down:%v", len(ipSucess)+len(ipFail), len(ipSucess), len(ipFail))

}

func pingCmd(v string) {
	command := "ping"
	args := "-c 2 -W 5 " + v
	// args := "-n 2 -w 5 " + v
	argArray := strings.Split(args, " ")
	cmds := exec.Command(command, argArray...)

	rets, err := cmds.Output()
	if err != nil {
		// fmt.Fprintf(os.Stderr, "The command failed to perform: %s (Command: %s, Arguments: %s)", err, command, args)
		panic(err)

	}
	ipSucess = append(ipSucess, v)
	// fmt.Printf("%v UP\n", v)
	fmt.Printf(string(rets[:]))

}

func operText(textfile string, a chan string) error {
	file, err := os.Open(textfile)
	if err != nil {
		log.Printf("Cannot open text file: %s, err: [%v]", textfile, err)
		return err
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text() // or
		a <- line
		// fmt.Printf("%s\n", line)
	}
	close(a)

	if err := scanner.Err(); err != nil {
		log.Printf("Cannot scanner text file: %s, err: [%v]", textfile, err)
		return err
	}

	return nil
}
